package com.jwiki.app.jkeeper.service.impl;

import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jwiki.app.jkeeper.common.CommonException;
import com.jwiki.app.jkeeper.controller.form.UserForm;
import com.jwiki.app.jkeeper.repository.mapper.UserMapper;
import com.jwiki.app.jkeeper.repository.model.UserModel;
import com.jwiki.app.jkeeper.service.BaseService;
import com.jwiki.app.jkeeper.service.UserService;

@Service
public class UserServiceImpl extends BaseService implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserModel getUserByName(String name) {
        UserModel model = new UserModel();
        model.setName(name);
        return userMapper.selectOne(model);
    }

    @Override
    public UserModel getUserByEmail(String email) {
        UserModel model = new UserModel();
        model.setEmail(email);
        return userMapper.selectOne(model);
    }

    @Override
    public boolean saveUser(UserForm form) {
        UserModel model = new UserModel();
        BeanUtils.copyProperties(form, model);
        if (StringUtils.isNotBlank(model.getPassword())) {
            model.setPassword(DigestUtils.md5Hex(model.getPassword()));
        }
        model.setUpdateBy(form.getName());

        if (model.getId() == null) {
            model.setCreateBy(form.getName());
            return userMapper.insert(model) > 0;
        } else {
            return userMapper.update(model) > 0;
        }
    }

    @Override
    public boolean savePassword(UserForm form) {
        UserModel model = userMapper.select(form.getId());
        if (model.getPassword().equals(DigestUtils.md5Hex(form.getPassword()))) {
            model.setPassword(DigestUtils.md5Hex(form.getNewPassword()));
            model.setUpdateTime(new Date());
            return userMapper.update(model) > 0;
        } else {
            throw new CommonException("旧密码不正确！");
        }
    }

}
